<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Category;
use App\Repositories\CategoryRepository;
use App\Article;
use App\Repositories\ArticleRepository;
use App\Feed;
use App\ArticleSub;
use App\FeedSub;
use DB;
use App\Repositories\FeedSubRepository;
use App\Repositories\ArticleSubRepository;

class ArticleController extends Controller
{
    /**
     * The note repository instance.
     *
     * @var NoteRepository
     */
    protected $categorys;
    
    protected $articles;
    
    protected $feedSubs;
    
    protected $articleSubs;

    /**
     * Create a new controller instance.
     *
     * @param  TaskRepository  $tasks
     * @return void
     */
    public function __construct( CategoryRepository $categorys, ArticleRepository $articles, FeedSubRepository $feedSubs, ArticleSubRepository $articleSubs)
    {
        $this->middleware('auth', ['except' => ['welcome']]);

        $this->categorys = $categorys;
        $this->articles = $articles;
        $this->articleSubs = $articleSubs;
        $this->articleSubs = $articleSubs;
    }
    
    public function welcome(Request $request)
    {
    	return view('articles.welcome', []);
    }
    /**
     * Display a list of all of the user's task.
     *
     * @param  Request  $request
     * @return Response
     */
    public function index(Request $request)
    {
    	$page_params = array();
    	
    	$categorys = $this->categorys->forUser($request->user());
    	if($request->has('status')){
    		$status = $request->status;
    	} else {
    		$status = 'unread';
    	}
    	$page_params['status'] = $status;
    	
    	$temp_counts = ArticleSub::select('feed_id',DB::raw('count(*) as total'))->where('status',$status)->groupBy('feed_id')->get();
    	$counts_info = array();
    	foreach ($temp_counts as $temp_count){
    		$counts_info[$temp_count['feed_id']] = $temp_count['total'];
    	}
    	
    	if($request->has('feed_id')){
    		$articleSubs = $this->articleSubs->forUserByStatusFeedId($request->user(), $status, $request->feed_id,$need_page=true);
    		$page_params['feed_id'] = $request->feed_id;
    	} else {
    		$articleSubs = $this->articleSubs->forUserByStatus($request->user(), $status,$need_page=true);
    	}
    	
    	if(count($articleSubs) == 0){
    		$recommend_feeds = Feed::where('user_id','!=' , $request->user()->id)->orderBy(\DB::raw('RAND()'))->take(4)->get();;
    	} else {
    		$recommend_feeds = array();
    	}
    	
        return view('articles.index', [
            'categorys' => $categorys,
        	'articleSubs' => $articleSubs,
        	'status' => $status,
        	'page_params' => $page_params,
        	'counts_info' => $counts_info,
        	'recommend_feeds' => $recommend_feeds,
        ]);
    }
    
    public function view(Request $request,Article  $article)
    {
        if ($request->ajax() || $request->wantsJson()) {
        	$resp = $this->responseJson(self::OK_CODE,$article);
        	return response($resp);
        } else {
        	return view('articles.view', [
    			'article' => $article,
    		]);
        }
    }
    
    public function star(Request $request,ArticleSub  $articleSub)
    {
    	$this->authorize('destroy', $articleSub);
    	 
    	if($articleSub->status == 'star'){
    		$articleSub->status = 'read';
    		$articleSub->update();
    	} else {
    		$articleSub->status = 'star';
    		$articleSub->update();
    	}
    	
    	if ($request->ajax() || $request->wantsJson()) {
    		$resp = $this->responseJson(self::OK_CODE,$articleSub->article);
    		return response($resp);
    	} else {
    		return view('articles.view', [
    			'article' => $articleSub->article,
    		]);
    	}
    }
    
    public function read(Request $request,ArticleSub  $articleSub)
    {
    	if($request->has('ids')){
			$id_arr = explode(',', $request->ids);
			foreach ($id_arr as $id){
				$articleSub = ArticleSub::where('id',$id)->where('user_id',$request->user()->id)->first();
				if(empty($articleSub)){
					continue;
				} else {
					$articleSub->status = 'read';
	    			$articleSub->update();
				}
			}
    	} else {
	    	$this->authorize('destroy', $articleSub);
	    	if(in_array($request->status,array('read','unread'))){
	    		$articleSub->status = 'read';
	    		$articleSub->update();
	    	}
    	}
    	 
    	if ($request->ajax() || $request->wantsJson()) {
    		$resp = $this->responseJson(self::OK_CODE,$articleSub->article);
    		return response($resp);
    	} else {
    		return view('articles.view', [
    				'article' => $articleSub->article,
    		]);
    	}
    }
    
    /**
     * Destroy the given task.
     *
     * @param  Request  $request
     * @param  Task  $task
     * @return Response
     */
    public function destroy(Request $request, ArticleSub $articleSub)
    {
        $this->authorize('destroy', $articleSub);

        $articleSub->delete();

        if ($request->ajax() || $request->wantsJson()) {
        	$resp = $this->responseJson(self::OK_CODE);
        	return response($resp);
        } else {
        	return redirect('/articles')->with('message', 'IT WORKS!');
        }
    }
}
